#!/bin/bash

# WARNING 1: probably contains bashisms galore.  If you don't have bash,
# please install it.

# NOTE 1: this script is run as root.

# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------

# BEGIN site-local changes

    # the full path to the new login shell to replace these users' existing shell
    new_shell="/usr/local/bin/gl-shell"

    my_chsh() {
        # please replace with appropriate command for your OS/distro.  This one is
        # suitable at least for Fedora, maybe others also
        chsh -s $new_shell $1 >&2
    }

    # remove these 2 lines after you have done your customisation
    [ -f /tmp/done.gl-shell-setup ] || { echo please customise $0 before using >&2; exit 1; }

# END site-local changes

# ------------------------------------------------------------------------------

die() { echo "FATAL: $@" >&2; exit 1; }

# ------------------------------------------------------------------------------

euid=$(perl -e 'print $>')
if [ "$euid" = "0" ]
then

    [ -n "$1" ] || die "need a valid username"
    user=$1
    id $user >/dev/null || die "need a valid username"

    # now fix up the user's login shell
    my_chsh $user

    pubkey="$PWD/$user.pub"
    [ -f "$pubkey" ] && {
        echo "$user.pub already exists.  Shell changed, exiting..." >&2
        exit 0
    }

    # drat... 'cd ~$user` doesn't work...
    cd $(bash -c "echo ~$user") || die "can't cd to $user's home directory"

    # now set up her rsa key, creating it if needed.  This will get used if
    # she comes in via password or without agent forwarding.
    [ -d .ssh ] || {
        mkdir .ssh
        chown $user .ssh
        chmod go-w  .ssh
    }

    [ -f .ssh/id_rsa.pub ] || {
        ssh-keygen -q -N "" -C $user@`hostname` -f .ssh/id_rsa >&2
        chown $user .ssh/id_rsa .ssh/id_rsa.pub
        chmod go-rw .ssh/id_rsa
        chmod go-w  .ssh/id_rsa.pub
    }

    # create alice.pub
    cat .ssh/id_rsa.pub > $pubkey

    exit 0

else

    die "needs to run as root"

fi
